package com.artemis.io;

import com.artemis.Archetype;
import com.artemis.ArchetypeBuilder;
import com.artemis.Entity;
import com.artemis.World;
import com.artemis.utils.IntBag;
import com.badlogic.gdx.utils.JsonValue;

import java.util.Arrays;

/**
 * Maintains the pool of entities to be laoded; ensures that the
 * entity id order matches the order in the json.
 */
public class EntityPoolFactory {
    protected final Archetype archetype;
    protected final World world;

    private IntBag pool = new IntBag();
    private int poolIndex;

    public EntityPoolFactory(World world) {
        this.world = world;
        archetype = new ArchetypeBuilder().build(world);
        world.inject(this);
    }

    void configureWith(int count) {
        poolIndex = 0;
        pool.setSize(0);
        pool.ensureCapacity(count);
        for (int i = 0; i < count; i++) {
            pool.add(world.create(archetype));
        }

        Arrays.sort(pool.getData(), 0, pool.size());
    }

    protected Entity createEntity(JsonValue jsonData) {
        return world.getEntity(pool.getData()[poolIndex++]);
    }

}
